﻿using Liju.Common;
using Liju.Model;
using LiJu.Db;
using LiJu.Model.Model;
using LiJu.Product;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LiJu
{
    public partial class ProductView : Form
    {
        #region 变量，定义
        private Font defaultFont = new Font("Microsoft YaHei", 9);
        LiJu.Product.ProductDetailControl productDetailControl = new LiJu.Product.ProductDetailControl();
        public List<ProductModel> Products = null;
        private Action<long> DeleteProductEvent = null;
        /// <summary>
        /// 页面类型
        /// </summary>
        private Enum ViewType;
        /// <summary>
        /// 获取菜单权限
        /// </summary>
        private SystemMenuRole systemMenuRole;
        #endregion
        public ProductView()
        {
            InitializeComponent();


            // 加载时启用默认双缓冲并提供无闪烁的图形呈现：
            this.DoubleBuffered = true;//设置本窗体
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲


            InitProductList();
            DeleteProductEvent += DeleteProductEventFunc;
        }

        /// <summary>
        /// 防止闪屏
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }

        private void ProductView_Load(object sender, EventArgs e)
        {
            try
            {
                Products = ProductDbHelper.GetPageDataProducts(pageSize, 1);
                UpdatePageControls();
                systemMenuRole = PageDataDto.SystemMenuRoleInfo();
                DeleteRestProductImg();
                InitProductData(Products);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"产品，ProductView_Load->{ex.Message}");
            }
        }
        #region 方法

        #region 导航栏
        /// <summary>
        /// 设置TableLayoutPanel指定行的高度
        /// </summary>
        /// <param name="layout">TableLayoutPanel</param>
        /// <param name="row">行号</param>
        /// <returns>行高</returns>
        public void SetTableLayoutRowHeight(TableLayoutPanel layout, int row, float height)
        {
            int count = layout.RowCount;
            if (row > count) return;

            for (int i = 0; i <= count; i++)
            {
                if (i == row)
                {
                    layout.RowStyles[i].Height = height;
                    return;
                }
            }
        }

        /// <summary>
        /// 更新导航标题
        /// </summary>
        private void UpdateNavigateTitle(ProductViewType type)
        {
            ViewType = type;
            if (ViewType.Equals(ProductViewType.ProductList))
            {
                lbl_ProductList.ForeColor = Color.Black;
                lbl_ProductMenu.Visible = false;
                lbl_ProductNext.Visible = false;
                productDetailControl.Visible = false;
                gdview_ProductList.Visible = true;
                TableLayoutPanelHelper.SetTableLayoutRowHeight(tbPanel_ProductNavigate, 1, 50);
                RefreshProductList();

            }
            else if (ViewType.Equals(ProductViewType.ProductAdd))
            {
                ReadProductParameters();
                lbl_ProductList.ForeColor = Color.Gray;
                lbl_ProductNext.ForeColor = Color.Gray;
                lbl_ProductMenu.ForeColor = Color.Black;
                lbl_ProductMenu.Visible = true;
                lbl_ProductNext.Visible = true;
                productDetailControl.ChangeProductView(type);
                productDetailControl.Visible = true;
                gdview_ProductList.Visible = false;
                lbl_ProductMenu.Text = ProductNavigateTitle.ProductAddTitle;
                TableLayoutPanelHelper.SetTableLayoutRowHeight(tbPanel_ProductNavigate, 1, 0);
                RefreshProductList();
            }
            else if (ViewType.Equals(ProductViewType.ProductEdit))
            {
                ReadProductParameters();
                lbl_ProductList.ForeColor = Color.Gray;
                lbl_ProductNext.ForeColor = Color.Gray;
                lbl_ProductMenu.ForeColor = Color.Black;
                lbl_ProductMenu.Visible = true;
                lbl_ProductNext.Visible = true;
                productDetailControl.ChangeProductView(type);
                productDetailControl.Visible = true;
                gdview_ProductList.Visible = false;
                lbl_ProductMenu.Text = ProductNavigateTitle.ProductEditTitle;
                TableLayoutPanelHelper.SetTableLayoutRowHeight(tbPanel_ProductNavigate, 1, 0);

            }
            else if (ViewType.Equals(ProductViewType.ProductDetail))
            {
                lbl_ProductList.ForeColor = Color.Gray;
                lbl_ProductNext.ForeColor = Color.Gray;
                lbl_ProductMenu.ForeColor = Color.Black;
                lbl_ProductMenu.Visible = true;
                lbl_ProductNext.Visible = true;
                productDetailControl.ChangeProductView(type);
                productDetailControl.Visible = true;
                gdview_ProductList.Visible = false;
                lbl_ProductMenu.Text = ProductNavigateTitle.ProductDetailTitle;
                TableLayoutPanelHelper.SetTableLayoutRowHeight(tbPanel_ProductNavigate, 1, 0);

            }
        }
        #endregion


        /// <summary>
        /// 添加测试数据
        /// </summary>
        private void InitProductData(List<ProductModel> products)
        {
            gdview_ProductList.Rows.Clear();
            for (int i = this.gdview_ProductList.Controls.Count - 1; i >= 0; i--)
            {
                Control control = this.gdview_ProductList.Controls[i];
                if (control is Label)
                {
                    control.Dispose();
                    this.gdview_ProductList.Controls.Remove(control);
                }
                else if (control is PictureBox)
                {
                    control.Dispose();
                    this.gdview_ProductList.Controls.Remove(control);
                }

            }
            this.gdview_ProductList.Controls.Clear();
            //设置行高
            gdview_ProductList.RowTemplate.Height = 40;
            for (int i = 0; i < products.Count; i++)
            {
                ProductModel product = products[i];
                // 添加一行数据
                gdview_ProductList.Rows.Add();
                // 为这行的各列赋值
                gdview_ProductList.Rows[i].Cells["Id"].Value = product.Id;
                gdview_ProductList.Rows[i].Cells["Num"].Value = currentPage > 1 ? (currentPage - 1) * pageSize + i + 1 : i + 1;
                gdview_ProductList.Rows[i].Cells["ProductName"].Value = product.ProductName;
                gdview_ProductList.Rows[i].Cells["BarCode"].Value = product.BarCode;
                gdview_ProductList.Rows[i].Cells["PictureNum"].Value = product.ImgNum;
                gdview_ProductList.Rows[i].Cells["TaskCount"].Value = product.TaskNum;
                gdview_ProductList.Rows[i].Cells["Status"].Value = product.Status == 0 ? "禁用" : "启用";
                gdview_ProductList.Rows[i].Cells["CreateTime"].Value = product.CreateTime;
                gdview_ProductList.Rows[i].Cells["Creater"].Value = product.Creater;

            }
            //循环遍历添加每行的控件
            for (int i = 0; i < gdview_ProductList.Rows.Count; i++)
            {
                MulAutoBtnEdit(i);
            }
            // 假设你要设置第一列的选中颜色
            DataGridViewColumn column = gdview_ProductList.Columns["Operate"];
            // 设置第一列选中单元格的背景颜色
            column.DefaultCellStyle.SelectionBackColor = Color.White;
            gdview_ProductList.ReadOnly = true;
            //显示行网格线，隐藏列网格线
            this.gdview_ProductList.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal;
            this.gdview_ProductList.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            this.gdview_ProductList.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            // 设置选中单元格的背景颜色
            gdview_ProductList.DefaultCellStyle.SelectionBackColor = System.Drawing.ColorTranslator.FromHtml("#BFEFFF");
            //设置选择模式为整行选择
            gdview_ProductList.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            // 设置选中单元格的前景颜色
            gdview_ProductList.DefaultCellStyle.SelectionForeColor = Color.Black;
            this.gdview_ProductList.DefaultCellStyle.Font = defaultFont;
        }


        /// <summary>
        /// 绘制单元格内的控件
        /// </summary>
        /// <param name="rowIndex"></param>
        private void MulAutoBtnEdit(int rowIndex)
        {
            //添加"详情","编辑","禁用","删除"按钮
            int index = this.gdview_ProductList.Columns["Operate"].Index;
            Label btnDetail = GetBtnByType("BtnDetail", "详情", rowIndex);
            Label btnEdit = GetBtnByType("BtnEdit", "编辑", rowIndex);
            Label btnForbidden = GetBtnByType("btnForbidden", "禁用", rowIndex);
            Label btnDel = GetBtnByType("BtnDel", "删除", rowIndex);
            if (systemMenuRole.Product_Add)
            {
                TableLayoutPanelHelper.SetTableLayoutRowHeight(tbPanel_ProductNavigate, 1, 50);
            }
            else
            {
                TableLayoutPanelHelper.SetTableLayoutRowHeight(tbPanel_ProductNavigate, 1, 0);
            }
            Rectangle rectangle = this.gdview_ProductList.GetCellDisplayRectangle(index, rowIndex, true);//获取当前单元格上的矩形区域
            btnDetail.Size = btnEdit.Size = btnDel.Size = btnForbidden.Size = new Size(rectangle.Width / 3 + 1, rectangle.Height);
            int controlCount = 0;
            if (systemMenuRole.Product_Check)
            {
                btnDetail.Location = new Point(rectangle.Left + 10, rectangle.Top + 8);
                this.gdview_ProductList.Controls.Add(btnDetail);
                controlCount++;
            }
            if (systemMenuRole.Product_Edit)
            {
                btnEdit.Location = new Point(rectangle.Left + btnDetail.Width * controlCount + 10, rectangle.Top + 8);
                this.gdview_ProductList.Controls.Add(btnEdit);
                controlCount++;
            }
            if (systemMenuRole.Product_State)
            {
                this.gdview_ProductList.Controls.Add(btnForbidden);
                btnForbidden.Location = new Point(rectangle.Left + btnDetail.Width * controlCount + 10, rectangle.Top + 8);
                controlCount++;
            }
            if (systemMenuRole.Product_Del)
            {
                btnDel.Location = new Point(rectangle.Left + btnDetail.Width * controlCount + 10, rectangle.Top + 8);
                this.gdview_ProductList.Controls.Add(btnDel);
            }

            //添加"产品图片"
            string productIdSter = gdview_ProductList.Rows[rowIndex].Cells["Id"].Value.ToString();
            long.TryParse(productIdSter, out long productId);
            List<ProductImgModel> productImgs = ProductImgDbHelper.GetAllProductImgByProductId(productId);
            index = this.gdview_ProductList.Columns["ProductImg"].Index;
            int picWidth = this.gdview_ProductList.Columns["ProductImg"].Width / 6 - 2;
            int num = 0;
            foreach (var productImg in productImgs)
            {
                string picFolder = Directory.GetCurrentDirectory() + $"\\Picture\\";
                string picName = productImg.Path;
                string picPath = Path.Combine(picFolder, picName);

                if (File.Exists(picPath))
                {
                    rectangle = this.gdview_ProductList.GetCellDisplayRectangle(index, rowIndex, true);//获取当前单元格上的矩形区域
                    if(rectangle.Width< picWidth * (num+1) + 2 * (num + 2))
                    {
                        break;
                    }
                    PictureBox btnPic = GetPictureByType($"btnPic{num}", picPath, rowIndex);
                    this.gdview_ProductList.Controls.Add(btnPic);

                    btnPic.Size = new Size(picWidth, rectangle.Height);
                    btnPic.Width = picWidth;
                    btnPic.Height = rectangle.Height - 15;
                    btnPic.Location = new Point(rectangle.Left + btnPic.Width * num + 2 * (num + 2), rectangle.Top + 3);
                    btnPic.SizeMode = PictureBoxSizeMode.StretchImage;
                    btnPic.Image = Image.FromFile(picPath);
                    num++;
                }

            }

        }
        /// <summary>
        /// 生成单元格产品图片控件
        /// </summary>
        /// <param name="picName"></param>
        /// <param name="picPath"></param>
        /// <param name="picRow"></param>
        /// <returns></returns>
        private PictureBox GetPictureByType(string picName, string picPath, int picRow)
        {
            PictureBox pic = new PictureBox();
            pic.Cursor = Cursors.Hand;
            pic.Tag = picPath;
            pic.AutoSize = true;
            pic.Click += pic_Click;
            return pic;
        }
        /// <summary>
        /// 产品图片使用电脑默认图片工具打开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pic_Click(object sender, EventArgs e)
        {
            if (sender is PictureBox)
            {
                PictureBox pic = (PictureBox)sender;
                string picPath = pic.Tag.ToString();
                if (!string.IsNullOrEmpty(picPath))
                {
                    System.Diagnostics.Process.Start(picPath);
                }
            }
        }

        /// <summary>
        /// 封装需要显示的控件
        /// </summary>
        /// <param name="strBtnName"></param>
        /// <param name="strBtnText"></param>
        /// <param name="rowIndex"></param>
        /// <returns></returns>
        private Label GetBtnByType(string strBtnName, string strBtnText, int rowIndex)
        {
            Label lab = new Label();
            lab.Name = strBtnName;

            if (strBtnName == "btnForbidden")
            {
                var statusStr = gdview_ProductList.Rows[rowIndex].Cells["Status"].Value?.ToString();
                if (statusStr == "禁用")
                {
                    lab.Text = "启用";
                }
                else if (statusStr == "启用")
                {
                    lab.Text = "禁用";
                }
            }
            else
            {
                lab.Text = strBtnText;
            }
            lab.ForeColor = strBtnName == "BtnDel" ? Color.Red : Color.FromArgb(64, 158, 255);
            lab.BackColor = Color.Transparent;
            lab.Cursor = Cursors.Hand;
            lab.Tag = rowIndex.ToString();
            lab.AutoSize = true;
            lab.Click += lblOperate_Click;
            return lab;
        }

        /// <summary>
        /// 控件对应的点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblOperate_Click(object sender, EventArgs e)
        {
            if (sender is Label)
            {
                Label btn = (Label)sender;
                int index = Convert.ToInt32(btn.Tag);
                string productIdStr = gdview_ProductList.Rows[index].Cells["Id"].Value?.ToString();
                long.TryParse(productIdStr, out long productId);
                if (btn.Name.Equals("BtnDetail"))
                {
                    if (productId > 0)
                    {
                        productDetailControl.Product = ProductDbHelper.GetProductById(productId);
                    }
                    UpdateNavigateTitle(ProductViewType.ProductDetail);
                }
                else if (btn.Name.Equals("BtnEdit"))
                {
                    if (productId > 0)
                    {
                        productDetailControl.Product = ProductDbHelper.GetProductById(productId);
                    }
                    UpdateNavigateTitle(ProductViewType.ProductEdit);
                }
                else if (btn.Name.Equals("btnForbidden"))
                {
                    if (btn.Text == "启用")
                    {
                        ProductDbHelper.UpdateProductStatus(productId, 1);
                    }
                    else
                    {
                        ProductDbHelper.UpdateProductStatus(productId, 0);
                    }
                    RefreshProductList();
                }
                else if (btn.Name.Equals("BtnDel"))
                {
                    if (MessageBox.Show("确定删除该产品?", "删除产品", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        if (productId > 0)
                        {
                            ProductDbHelper.DeleteProduct(productId);
                            ProductImgDbHelper.DeleteProductImgByProductId(productId);
                            TaskDbHelper.DeleteTaskByProductId(productId);
                            RefreshProductList();
                            DeleteProductEvent?.Invoke(productId);
                        }

                    }
                }
            }
        }

        /// <summary>
        /// 初始化产品列表
        /// </summary>
        private void InitProductList()
        {
            try
            {
                ViewType = ProductViewType.ProductList;
                productDetailControl.Dock = DockStyle.Fill;
                productDetailControl.NavigateEvent += NavigateEventFunc;
                panel_Product.Controls.Add(productDetailControl);
                ReadProductParameters();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"InitProductDetails->{ex.Message}");
            }
        }

        /// <summary>
        /// 读取产品参数
        /// </summary>
        private void ReadProductParameters()
        {
            List<DDKScrewParam> screwdriverParams = Bll.GetAllDDKParameter();
            List<SleeveModel> sleeveModels = Bll.GetAllSleeveModels();
            List<ScrewModel> screwModels = Bll.GetAllScrewModels();

            productDetailControl.screwdriverParams = screwdriverParams;
            productDetailControl.sleeveModels = sleeveModels;
            ScrewModel screwModel = new ScrewModel()
            {
                Id=0,
                Model="无需螺丝"
            };
            screwModels.Add(screwModel);
            productDetailControl.screwModels = screwModels;
        }

        /// <summary>
        /// 刷新产品列表
        /// </summary>
        private void RefreshProductList()
        {
            Products = ProductDbHelper.GetPageDataProducts(pageSize, currentPage);
            UpdatePageControls();
            InitProductData(Products);
        }

        /// <summary>
        /// 删除多余产品图片
        /// </summary>
        private void DeleteRestProductImg()
        {
            string imgPath = Directory.GetCurrentDirectory() + $"\\Picture\\";
            string[] filePaths = Directory.GetFiles(imgPath);
            List<string> allImages = new List<string>();
            foreach (var product in Products)
            {
                List<ProductImgModel> productImgs = ProductImgDbHelper.GetAllProductImgByProductId(product.Id);
                foreach (var picImgModel in productImgs)
                {
                    allImages.Add(picImgModel.Path);
                }
            }
            foreach (string picPath in filePaths)
            {
                string picName = Path.GetFileName(picPath);
                if (!allImages.Exists(p => p == picName))
                {
                    try
                    {
                        File.Delete(picPath);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
        }

        #region 事件方法
        /// <summary>
        /// 产品详情页导航事件
        /// </summary>
        /// <param name="type"></param>
        private void NavigateEventFunc(ProductViewType type)
        {
            UpdateNavigateTitle(type);
        }
        /// <summary>
        /// 删除产品事件方法
        /// </summary>
        private void DeleteProductEventFunc(long productId)
        {
            try
            {
                List<ProductImgModel> productImgs = ProductImgDbHelper.GetAllProductImgByProductId(productId);
                foreach (ProductImgModel productImgModel in productImgs)
                {
                    string picFolder = Directory.GetCurrentDirectory() + $"\\Picture\\";
                    string picName = productImgModel.Path;
                    string picPath = Path.Combine(picFolder, picName);
                    if (File.Exists(picPath))
                    {
                        File.Delete(picPath);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"DeleteProductEventFunc->{ex.Message}");
            }


        }
        #endregion

        #endregion

        /// <summary>
        /// 添加产品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_AddProduct_Click(object sender, EventArgs e)
        {
            int maxId = ProductDbHelper.GetMaxNewAddProductId();
            productDetailControl.Product.Id = maxId;
            UpdateNavigateTitle(LiJu.Product.ProductViewType.ProductAdd);
        }

        /// <summary>
        /// 切换产品列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lbl_ProductList_Click(object sender, EventArgs e)
        {
            UpdateNavigateTitle(LiJu.Product.ProductViewType.ProductList);
        }
        /// <summary>
        /// 设置鼠标悬浮行的背景和前景颜色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gdview_ProductList_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                gdview_ProductList.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.AliceBlue;
            }
        }
        /// <summary>
        /// 鼠标离开时恢复默认颜色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gdview_ProductList_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                gdview_ProductList.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
            }
        }
        /// <summary>
        /// 导出选中产品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExportSelectProduct_Click(object sender, EventArgs e)
        {
            ExportProduct(false);
        }
        /// <summary>
        /// 导出全部产品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExportAllProduct_Click(object sender, EventArgs e)
        {
            ExportProduct(true);
        }
        /// <summary>
        /// 导出产品
        /// </summary>
        /// <param name="isAll">0选中，1全部</param>
        private void ExportProduct(bool isAll)
        {
            var exportPath = ConfigurationManager.AppSettings["ExportPath"].ToString();
            DataTable dt = null;
            if (isAll)
            {
                dt = ExcelHelper.ListToDataTable<ProductModel>(Products);
            }
            else
            {
                List<ProductModel> exportProducts = new List<ProductModel>();
                for (int i = 0; i < gdview_ProductList.Rows.Count; i++)
                {
                    if(gdview_ProductList.Rows[i].Selected)
                    {
                        long.TryParse(gdview_ProductList.Rows[i].Cells["Id"].Value?.ToString(), out long productId);
                        exportProducts.Add(ProductDbHelper.GetProductById(productId));
                    }
                }
                if(exportProducts.Count>0)
                {
                    dt = ExcelHelper.ListToDataTable<ProductModel>(exportProducts);
                }
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                List<ProductImgModel> imgs = new List<ProductImgModel>();
                List<TaskModel> tasks = new List<TaskModel>();
                foreach (DataRow item in dt.Rows)
                {
                    long.TryParse(item["Id"].ToString(), out long productId);
                    imgs.AddRange(ProductImgDbHelper.GetAllProductImgByProductId(productId));
                    tasks.AddRange(TaskDbHelper.GetAllTaskByProductIdOrderNum(productId));
                }
                //string filePath;
                //SaveFileDialog saveFileDialog = new SaveFileDialog();
                //saveFileDialog.Filter = "CSV files (*.csv)|*.csv";
                //saveFileDialog.FilterIndex = 0;
                //if (saveFileDialog.ShowDialog() == DialogResult.OK)
                //{
                //    filePath = saveFileDialog.FileName;
                //}
                //else
                //{
                //    return;
                //}
                //ExcelHelper.ExportDataTableToCSV(filePath, new[] { dt, ExcelHelper.ListToDataTable<ProductImgModel>(imgs), ExcelHelper.ListToDataTable<TaskModel>(tasks) });
                //MessageBox.Show($"{dt.Rows.Count}个产品导出成功！");

                //配置位置导出路径
                string filePath;
                if (string.IsNullOrEmpty(exportPath))
                {
                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.Filter = "CSV files (*.csv)|*.csv";
                    saveFileDialog.FilterIndex = 0;
                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        filePath = saveFileDialog.FileName;//\\10.17.2.101\temp
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    //filePath = string.Concat(exportPath, DateTime.Now.ToString("yyyyMMddHHmmss"), ".csv");
                    string tempName = isAll ? DateTime.Now.ToString("yyyyMMddHHmmss") : dt.Rows[0]["ProductName"].ToString();
                    filePath = string.Concat(exportPath, tempName, ".csv");
                }

                try
                {
                    ExcelHelper.ExportDataTableToCSV(filePath, new[] { dt, ExcelHelper.ListToDataTable<ProductImgModel>(imgs), ExcelHelper.ListToDataTable<TaskModel>(tasks) });
                    if (isAll)
                    {
                        MessageBox.Show($"{dt.Rows.Count}个产品导出成功！");
                    }
                    else
                    {
                        MessageBox.Show($"产品：\"{dt.Rows[0]["ProductName"]}\"导出成功！");
                    }
                }
                catch (UnauthorizedAccessException ex)
                {
                    MessageBox.Show($"导出异常：{ex.Message}");
                }
            }
            else
            {
                MessageBox.Show($"没有可导出的产品或未选中导出产品！");
            }
        }
        /// <summary>
        /// 导入产品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnImportProduct_Click(object sender, EventArgs e)
        {
            var exportPath = ConfigurationManager.AppSettings["ExportPath"].ToString();
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "CSV files (*.csv)|*.csv";
            openFileDialog.InitialDirectory = exportPath;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                AddImportProduct(ExcelHelper.ImportCsvToTables(openFileDialog.FileName), openFileDialog.FileName);
            }
            else
            {
                return;
            }
        }
        /// <summary>
        /// 添加导入产品
        /// </summary>
        /// <param name="dataTables"></param>
        private void AddImportProduct(DataTable[] dataTables,string fileName)
        {
            if (dataTables.Count() > 0)
            {
                var _count = 0; //计数器
                foreach (DataRow drProduct in dataTables[0].Rows)
                {
                    var existProduct = ProductDbHelper.GetProductByCode(drProduct["BarCode"].ToString());
                    long.TryParse(drProduct["Id"].ToString(), out long exportProductId);
                    if (existProduct != null)
                    {
                        DialogResult dialogResult = MessageBox.Show($"产品已存在！产品名称：{existProduct.ProductName}，型号：{existProduct.BarCode}", "是否覆盖？", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (dialogResult == DialogResult.Yes)
                        {
                            // 读取配置
                            string userName = ConfigurationManager.AppSettings["UserName"];
                            //修改产品
                            ProductModel prodModel = new ProductModel();
                            prodModel.Id = existProduct.Id;
                            prodModel.ProductName = drProduct["ProductName"].ToString();
                            prodModel.BarCode = drProduct["BarCode"].ToString();
                            prodModel.TaskNum = Convert.ToInt32(drProduct["TaskNum"]);
                            prodModel.ImgNum = Convert.ToInt32(drProduct["ImgNum"]);
                            prodModel.UpdateTime = DateTime.Now.ToString();
                            prodModel.Status = Convert.ToInt32(drProduct["Status"]);
                            prodModel.UpdateUser = userName;
                            if(ProductDbHelper.UpdateProduct(prodModel))
                                _count++;

                            //删除所有旧产品图片
                            ProductImgDbHelper.DeleteProductImgByProductId(existProduct.Id);
                            //添加新产品图片
                            foreach (DataRow drImg in dataTables[1].Rows)
                            {
                                long.TryParse(drImg["ProductId"].ToString(), out long _prodId);
                                if (_prodId == exportProductId)
                                {
                                    ProductImgModel imgModel = new ProductImgModel();
                                    imgModel.ProductId = prodModel.Id;
                                    imgModel.WorkNum = Convert.ToInt32(drImg["WorkNum"]);
                                    imgModel.ImgIndex = Convert.ToInt32(drImg["ImgIndex"]);
                                    imgModel.Path = drImg["Path"].ToString();
                                    imgModel.Status = Convert.ToInt32(drImg["Status"]);
                                    ProductImgDbHelper.AddProductImg(imgModel);
                                }
                            }
                            //删除所有旧产品任务
                            TaskDbHelper.DeleteTaskByProductId(existProduct.Id);
                            //添加产品任务
                            foreach (DataRow drTask in dataTables[2].Rows)
                            {
                                long.TryParse(drTask["ProductId"].ToString(), out long _prodId);
                                if (_prodId == exportProductId)
                                {
                                    TaskModel taskModel = new TaskModel();
                                    taskModel.WorkNum = Convert.ToInt32(drTask["WorkNum"]);
                                    taskModel.Num = Convert.ToInt32(drTask["Num"]);
                                    taskModel.ProductId = prodModel.Id;
                                    taskModel.ProductImgNum = Convert.ToInt32(drTask["ProductImgNum"]);
                                    taskModel.ScrewControlLocation = drTask["ScrewControlLocation"].ToString();
                                    taskModel.ScrewLocation = drTask["ScrewLocation"].ToString();
                                    taskModel.ErrorLimit = Convert.ToDouble(drTask["ErrorLimit"]);
                                    taskModel.RadiusError = Convert.ToDouble(drTask["RadiusError"]);
                                    taskModel.ScrewDriverParam = Convert.ToInt32(drTask["ScrewDriverParam"]);
                                    taskModel.SleeveModel = Convert.ToInt32(drTask["SleeveModel"]);
                                    taskModel.ScrewModel = Convert.ToInt32(drTask["ScrewModel"]);
                                    taskModel.Skip = Convert.ToInt32(drTask["Skip"]);
                                    taskModel.Status = Convert.ToInt32(drTask["Status"]);
                                    taskModel.TightenPrepare = Convert.ToInt32(drTask["TightenPrepare"]);
                                    TaskDbHelper.AddProductTask(taskModel);
                                }
                            }
                        }
                    }
                    else
                    {
                        // 读取配置
                        string userName = ConfigurationManager.AppSettings["UserName"];
                        //添加产品
                        ProductModel prodModel = new ProductModel();
                        prodModel.Id = ProductDbHelper.GetMaxNewAddProductId();
                        prodModel.ProductName = drProduct["ProductName"].ToString();
                        prodModel.BarCode = drProduct["BarCode"].ToString();
                        prodModel.TaskNum = Convert.ToInt32(drProduct["TaskNum"]);
                        prodModel.ImgNum = Convert.ToInt32(drProduct["ImgNum"]);
                        prodModel.CreateTime = DateTime.Now.ToString();
                        prodModel.Status = Convert.ToInt32(drProduct["Status"]);
                        prodModel.Creater = userName;
                        if (ProductDbHelper.AddProduct(prodModel))
                            _count++;

                        //添加产品图片
                        foreach (DataRow drImg in dataTables[1].Rows)
                        {
                            long.TryParse(drImg["ProductId"].ToString(), out long _prodId);
                            if (_prodId == exportProductId)
                            {
                                ProductImgModel imgModel = new ProductImgModel();
                                imgModel.ProductId = prodModel.Id;
                                imgModel.WorkNum = Convert.ToInt32(drImg["WorkNum"]);
                                imgModel.ImgIndex = Convert.ToInt32(drImg["ImgIndex"]);
                                imgModel.Path = drImg["Path"].ToString();
                                imgModel.Status = Convert.ToInt32(drImg["Status"]);
                                ProductImgDbHelper.AddProductImg(imgModel);
                            }
                        }
                        //添加产品任务
                        foreach (DataRow drTask in dataTables[2].Rows)
                        {
                            long.TryParse(drTask["ProductId"].ToString(), out long _prodId);
                            if (_prodId == exportProductId)
                            {
                                TaskModel taskModel = new TaskModel();
                                taskModel.WorkNum = Convert.ToInt32(drTask["WorkNum"]);
                                taskModel.Num = Convert.ToInt32(drTask["Num"]);
                                taskModel.ProductId = prodModel.Id;
                                taskModel.ProductImgNum = Convert.ToInt32(drTask["ProductImgNum"]);
                                taskModel.ScrewControlLocation = drTask["ScrewControlLocation"].ToString();
                                taskModel.ScrewLocation = drTask["ScrewLocation"].ToString();
                                taskModel.ErrorLimit = Convert.ToDouble(drTask["ErrorLimit"]);
                                taskModel.RadiusError = Convert.ToDouble(drTask["RadiusError"]);
                                taskModel.ScrewDriverParam = Convert.ToInt32(drTask["ScrewDriverParam"]);
                                taskModel.SleeveModel = Convert.ToInt32(drTask["SleeveModel"]);
                                taskModel.ScrewModel = Convert.ToInt32(drTask["ScrewModel"]);
                                taskModel.Skip = Convert.ToInt32(drTask["Skip"]);
                                taskModel.Status = Convert.ToInt32(drTask["Status"]);
                                taskModel.TightenPrepare = Convert.ToInt32(drTask["TightenPrepare"]);
                                TaskDbHelper.AddProductTask(taskModel);
                            }
                        }
                    }
                }
                if (_count > 0)
                {
                    RefreshProductList();
                    MessageBox.Show($"{_count}个产品导入成功！");
                }
            }
            else
            {
                MessageBox.Show($"产品导入失败！请检查导入文件：{fileName}");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SearchProject_Click(object sender, EventArgs e)
        {
            string productName = txt_ProductName.Text == "请输入" ? null : txt_ProductName.Text;

            Products = ProductDbHelper.GetAllProducts();
            List<ProductModel> productrecords = Products;

            gdview_ProductList.Rows.Clear();

            if (!string.IsNullOrEmpty(productName))
            {
                productrecords = Products.FindAll(o => o.ProductName.Contains(productName));
            }

            InitProductData(productrecords);
        }

        private void SearchProduct_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                btn_SearchProject_Click(sender, e);
            }
        }

        private void btn_Reset_Click(object sender, EventArgs e)
        {
            currentPage = 1;
            Products = ProductDbHelper.GetPageDataProducts(pageSize, 1);
            UpdatePageControls();
            List<ProductModel> productrecords = Products;
            gdview_ProductList.Rows.Clear();
            InitProductData(productrecords);
        }
        #region 分页查询  add zhl
        private int pageSize = 15;
        private int currentPage = 1;
        private int totalPage = 0;
        //private DataTable bindDgvData;
        /// <summary>
        /// 首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFirst_Click(object sender, EventArgs e)
        {
            MoveToPage(1);
        }
        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrevious_Click(object sender, EventArgs e)
        {
            MoveToPage(currentPage - 1);
        }
        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNext_Click(object sender, EventArgs e)
        {
            MoveToPage(currentPage + 1);
        }
        /// <summary>
        /// 尾页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLast_Click(object sender, EventArgs e)
        {
            MoveToPage((int)Math.Ceiling(totalPage / (double)pageSize));
        }

        private void MoveToPage(int page)
        {
            currentPage = page;
            InitProductData(GetPageData());
            UpdatePageControls();
        }
        /// <summary>
        /// 更新分页控件状态
        /// </summary>
        private void UpdatePageControls()
        {
            totalPage = ProductDbHelper.GetTotalRowCount();
            btnFirst.Enabled = currentPage > 1;
            btnPrevious.Enabled = currentPage > 1;
            btnNext.Enabled = (currentPage * pageSize) < totalPage;
            btnLast.Enabled = (currentPage * pageSize) < totalPage;
        }
        /// <summary>
        /// 获取当前页的数据
        /// </summary>
        /// <param name="_products"></param>
        /// <returns></returns>
        private List<ProductModel> GetPageData()
        {
            List<ProductModel> findProducts = ProductDbHelper.GetPageDataProducts(pageSize, currentPage);
            return findProducts;
        }
        #endregion
    }
}
